﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Controls;
using UIWindows.Commands;
using UIWindows.Domains;
using UIWindows.Views.DeviceConfigView;
using XingLucifer.IBase.Enums;
using System.Collections.ObjectModel;
using UIWindows.GlobalStatics;
using System.Net.Sockets;
using XingLucifer.IBase.Models;
using UIWindows.Domains.BroadcastDeviceObject;
using XingLucifer.IBase;
using UIWindows.Enums;
using MaterialDesignThemes.Wpf;
using UIWindows.Models.Devices;
using UIWindows.Views.Dialogs;
using UIWindows.ViewModels.Dialogs;
using UIWindows.Tools.Helper;
using static System.Formats.Asn1.AsnWriter;
using System.Threading;
using UIWindows.Views;
using UIWindows.Services;
using static NewLife.Remoting.ApiHttpClient;
using NewLife.Xml;
using System.Net.NetworkInformation;

namespace UIWindows.ViewModels
{
    public class DeviceConfigViewModel : ViewModelBase, IViewStatus
    {
        private List<UserControl> _deviceConfigView;
        #region 双向绑定属性
        /// <summary>
        /// 视图
        /// </summary>
        public UserControl ViewContent
        {
            get { return _viewContent; }
            set { SetProperty(ref _viewContent, value); }
        }
        public ObservableCollection<string> ServiceNameList { get; set; }

        public IEnumerable<TaskTypes> TaskTypeList
        {
            get
            {
                foreach (TaskTypes c in (TaskTypes[])Enum.GetValues(typeof(TaskTypes)))
                {
                    yield return c;
                }
            }
        }
        public IEnumerable<DeviceTypes> Foods
        {
            get
            {
                foreach (DeviceTypes c in (DeviceTypes[])Enum.GetValues(typeof(DeviceTypes)))
                {
                    yield return c;
                }
            }
        }
        public ObservableCollection<SerialServerModel> DeviceList { get; set; }
        /// <summary>
        /// 是否是多设备
        /// </summary> 
        public bool IsDevices { get; set; }
        public bool IsNet { get; set; } = true;
        public DeviceTypes Types { get; set; }

        public string StartAddress { get; set; }
        public int StartProt { get; set; }
        public string EndAddress { get; set; }
        public int EndPort { get; set; }
        public string ServiceName { get; set; }
        public TaskTypes TaskType { get; set; }
        public DeviceConfigStatic MyDevice { get; set; }
        public TemporaryStatic Temporary { get; set; }
        public DeviceConfigStatic _deviceConfigStatic { get; set; }
        #endregion
        #region 私有属性
        private UserControl _viewContent;
        private SystemConfigStatic ConfigStatic;
        #endregion

        public DeviceConfigViewModel(SystemConfigStatic configStatic, DeviceConfigStatic myDevice, TemporaryStatic temporaryStatic, DeviceConfigStatic deviceConfigStatic)
        {
            _deviceConfigView = new List<UserControl>
            {
                new NICConfiguration() { DataContext = new DeviceConfig.NICConfigurationVModel() },
                new SerialServer() { DataContext = new DeviceConfig.SerialServerVModel() },
                new DeviceInit() { DataContext = new DeviceConfig.DeviceInitVModel() },
                new PLCTest() { DataContext = new DeviceConfig.PLCTestVModel() }
            };
            ViewContent = _deviceConfigView[0];
            ServiceNameList = new ObservableCollection<string>();
            ConfigStatic = configStatic;
            MyDevice = myDevice;
            Temporary = temporaryStatic;
            _deviceConfigStatic = deviceConfigStatic;
            Task.Run(() =>
            {
                Ping ping = new Ping();

                while (true)
                {
                    if (MyDevice.DeviceList.Count != 0)
                    {
                        string errMessage = "";
                        errMessage = "设备掉线：";
                        try
                        {
                            //bool isErr = false;
                            foreach (var model in MyDevice.DeviceList)
                            {
                                if (!model.IsSocket || model.Index == 999) { continue; }
                                try
                                {
                                    var pingReply = ping.Send(model.IPCOM, 500);
                                    model.PingTime = pingReply.RoundtripTime;
                                    model.ICMPResult = pingReply.Status;
                                    model.IsOnline = model.ICMPResult == IPStatus.Success;
                                    model.PingNGCount = model.ICMPResult == IPStatus.Success ? 0 : model.PingNGCount + 1;
                                    if(model.PingNGCount == 5 && model.Index != 999)
                                    {
                                       
                                        TaskService.Instance.SwitchOFF();
                                        Models.Devices.DeviceClientModel? device = _deviceConfigStatic.DeviceList.FirstOrDefault(x => x.Index == model.Index);
                                        $"序号:[{model.Index}]{device?.ServiceName} IP:[{model.IPCOM}] 端口:[{model.Port}]设备通信异常,请检查网线！！！".RunLog(MessageLevelType.错误);
                                    }else if (model.PingNGCount > 5 && model.Index != 999)
                                    {
                                        errMessage += model.ServiceName + "、";
                                        // isErr = true;
                                        continue;
                                    }
                                }
                                catch (Exception ex)
                                {
                                    $"设备[{model.DeviceType}] 序号[{model.Index}] IP[{model.IPCOM}] 端口号[{model.Port}] 异常信息：{ex}".RunLog(MessageLevelType.警告);
                                    //errMessage +="、" +model.ServiceName;
                                    //isErr = true;
                                    errMessage += model.ServiceName+ "、";
                                }
                                //if (isErr)
                                //{
                                //    configStatic.SCM.HomeMessage = errMessage;
                                //}
                                //else { 
                                //}
                            }
                        }
                        catch (Exception)
                        {
                            Console.WriteLine();
                        }
                        var serviceList = Temporary.LinkList.FirstOrDefault(x => x.ServiceName == "设备状态");
                        if (serviceList != null)
                        {
                            serviceList.Status = !MyDevice.DeviceList.Any(x => x.PingNGCount > 1 && x.Index != 999);
                           
                        }
                        else
                        {
                           
                        }
                        if(errMessage == "设备掉线：" && !configStatic.SCM.HomeMessage.Contains( "设备连接失败："))
                        {
                            configStatic.SCM.HomeMessage = "当前上位机未运行，请点击右上角运行按钮";
                        }
                        else if(!configStatic.SCM.HomeMessage.Contains("设备连接失败："))
                        {
                            configStatic.SCM.HomeMessage = errMessage.TrimEnd('、')+"请检查设备是否开机";
                        }
                        
                    }
                    Thread.Sleep(500);
                }
            });
        }

        /// <summary>
        /// 切换视图
        /// </summary>
        public DelegateCommand<RadioButton> ViewToggle => new DelegateCommand<RadioButton>(sender =>
        {
            switch (sender.Content.ToString())
            {
                case "网卡配置":
                    ViewContent = _deviceConfigView[0];
                    break;
                case "设备扫描":
                    ViewContent = _deviceConfigView[1];
                    break;
                case "设备配置":
                    ViewContent = _deviceConfigView[2];
                    break;
                case "PLC测试":
                    ViewContent = _deviceConfigView[3];
                    break;
                case "通信测试":

                    break;

            }
        });

        public DelegateCommand AfterWeighingServer => new DelegateCommand(() =>
        {
            if (Temporary.IsRunStatus)
            {
                "设备在运行中，不可修改！！！".MessageDialogs(MessageLevelType.警告, true, PopUpTypes.Global);
                return;
            }
            if (MyDevice.DeviceList.Any(x => x.ServiceName == ServiceName && x.TaskType == TaskTypes.扫描信号) && TaskType == TaskTypes.扫描信号)
            {
                "相同服务名只能存在一个[扫描信号]任务".MessageDialogs(MessageLevelType.警告, true, PopUpTypes.Global);
                return;
            }
            if (IsDevices)
            {
                MyDevice.AddDevices(StartAddress, StartProt.ToString(), EndAddress, EndPort.ToString(), IsNet, Types, TaskType, ServiceName);
            }
            else
            {
                MyDevice.Add(StartAddress, StartProt, StartProt, IsNet, Types, TaskType, ServiceName);
            }
            ObservableCollection<DeviceClientModel> deviceClientModels = new ObservableCollection<DeviceClientModel>();
            foreach (var task in Enum.GetValues<XingLucifer.IBase.Enums.TaskTypes>())
            {
                foreach (var item in Enum.GetValues<XingLucifer.IBase.Enums.DeviceTypes>())
                {
                    foreach (var name in ServiceNameList)
                    {
                        var list = MyDevice.DeviceList.Where(x => x.DeviceType == item && x.ServiceName == name && x.TaskType == task).ToArray();
                        if (list == null) { continue; }
                        for (int i = 0; i < list.Count(); i++)
                        {
                            deviceClientModels.Add(list[i]);
                        }
                    }
                }
            }
            MyDevice.DeviceList.Clear();
            foreach (var item in deviceClientModels)
            {
                MyDevice.DeviceList.Add(item);
            }
            MyDevice.Save();
        }, AuthorityTypes.管理员_参照 | AuthorityTypes.超级管理员_参照);

        public DelegateCommand<DeviceClientModel> DeviceConfigMouseDoubleClick => new DelegateCommand<DeviceClientModel>(sender =>
        {
            if (sender == null) { return; }
            if (Temporary.IsRunStatus)
            {
                "设备在运行中，不可修改！！！".MessageDialogs(MessageLevelType.警告, false, PopUpTypes.Global);
                return;
            }
            if (ViewContent.DataContext is DeviceConfig.IDeviceViewModel sendeModel)
            {
                sendeModel.SendModel(sender);
                return;
            }
            _ = DialogHost.Show(new DeviceModify() { DataContext = new DeviceModifyVModel(sender, ConfigStatic, MyDevice) }, PopUpTypes.Global.ToString());
        }, AuthorityTypes.管理员_参照 | AuthorityTypes.超级管理员_参照);

        private Action<DeviceClientModel, DeviceClientModel> _copy;

        public DelegateCommand<ListView> SelectDelete => new DelegateCommand<ListView>(sender =>
        {
            if (_copy == null)
            {
                _copy = ConversionHelper.CopyClass<DeviceClientModel, DeviceClientModel>();
            }
            if (Temporary.IsRunStatus)
            {
                "设备在运行中，不可修改！！！".MessageDialogs(MessageLevelType.警告, true, PopUpTypes.Global);
                return;
            }
            List<DeviceClientModel> models = new List<DeviceClientModel>();
            foreach (var item in sender.SelectedItems)
            {
                DeviceClientModel model = new DeviceClientModel();
                _copy.Invoke(item as DeviceClientModel, model);
                models.Add(model);
            }
            foreach (var item in models)
            {
                var model = MyDevice.DeviceList.FirstOrDefault(x => x.IsSocket == item.IsSocket && x.TaskType == item.TaskType
                    && x.ServiceName == item.ServiceName
                    && x.Index == item.Index
                    && x.DeviceType == item.DeviceType
                    && x.Port == item.Port
                    && x.IPCOM == item.IPCOM);
                if (model != null)
                {
                    MyDevice.DeviceList.Remove(model);
                }
            }
            MyDevice.Save();
        }, AuthorityTypes.管理员_参照 | AuthorityTypes.超级管理员_参照);

        public object KLList { get; set; }

        public DelegateCommand<ListView> SelectDisable => new DelegateCommand<ListView>(sender =>
        {
            if (Temporary.IsRunStatus)
            {
                "设备在运行中，不可修改！！！".MessageDialogs(MessageLevelType.警告, true, PopUpTypes.Global);
                return;
            }
            foreach (var item in sender.SelectedItems)
            {
                (item as DeviceClientModel).Index = 999;
            }
            MyDevice.Save();
        }, AuthorityTypes.管理员_参照 | AuthorityTypes.超级管理员_参照);

        public void Load()
        {
            foreach (var item in ConfigStatic.SignalList)
            {
                ServiceNameList.Add(item.Name);
            }
        }

        public void UnLoad()
        {
            ServiceNameList.Clear();
        }
    }
}
